import 'package:yaml/yaml.dart';

extension ListExtension<E> on Iterable<E> {
  E? get lastOrNull => isNotEmpty ? last : null;

  E? firsOrNull(bool Function(E element) test) {
    for (E element in this) {
      if (test(element)) return element;
    }
    return null;
  }

  Map<T, List<E>> groupBy<T>(T Function(E element) key) {
    var map = <T, List<E>>{};
    for (var element in this) {
      (map[key(element)] ??= []).add(element);
    }
    return map;
  }
}

extension YamlListExt on YamlList? {
  List<T> forList<T>({T Function(dynamic)? convert}) {
    final yList = this;
    if (yList == null || yList.isEmpty) return List.empty();
    return yList.value.map((e) {
      if (convert == null) return e as T;
      return convert(e);
    }).toList();
  }
}
